package io.dshubs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.dshubs.commons.mybatis.service.impl.BaseServiceImpl;
import io.dshubs.commons.security.user.SecurityUser;
import io.dshubs.dao.SysUserArchiveCategoryMapper;
import io.dshubs.entity.SysUserArchiveCategory;
import io.dshubs.service.SysUserArchiveCategoryService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: yu
 * @Date: 2021/08/18/11:44
 */
@Service
public class SysUserArchiveCategoryServiceImpl extends BaseServiceImpl<SysUserArchiveCategoryMapper, SysUserArchiveCategory> implements SysUserArchiveCategoryService {
    /**
     * 保存或修改
     *
     * @param userId         用户id
     * @param categoryIdList 分类idList
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(Long userId, List<Long> categoryIdList) {
        this.deleteByUserId(userId);
        if (CollectionUtils.isEmpty(categoryIdList)) {
            return;
        }
        for (Long categoryId : categoryIdList) {
            SysUserArchiveCategory entity = new SysUserArchiveCategory();
            entity.setUserId(userId);
            entity.setCategoryId(categoryId);
            this.insert(entity);
        }
    }

    /**
     * 根据用户id删除
     *
     * @param userId 用户id
     */
    @Override
    public void deleteByUserId(Long userId) {
        baseDao.deleteByUserId(userId);
    }

    @Override
    public List<Long> list() {
        return getArchiveCategoryIdList(SecurityUser.getUserId());
    }

    @Override
    public List<Long> getArchiveCategoryIdList(Long id) {
        List<SysUserArchiveCategory> archiveCategoryList = baseDao.selectList(new QueryWrapper<SysUserArchiveCategory>().eq("user_id", id));
        if(CollectionUtils.isNotEmpty(archiveCategoryList)) {
            return archiveCategoryList.stream().map(SysUserArchiveCategory::getCategoryId).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }
}
